#import "Button.h"
#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
#import <CoreFoundation/CoreFoundation.h>
#import "AppDaemon.h"


@implementation SnapButton
- (id) initWithParent:(id)parent
{
	mParent = parent;
	mConfig = [Config singleton];
	_x = [mConfig x];
	_y = [mConfig y];

    tickIntervalM = 0.1f; // start with long tick interval
    [super initWithContentRect: CGRectMake(0.0f, 0.0f, BUTTON_WIDTH , BUTTON_HEIGHT)];

    viewM = [[UIImageView alloc] init];
    [viewM setTransform: CGAffineTransformIdentity];
    [viewM setImage:[UIImage applicationImageNamed: @"Button.png"]];
	[self Reset];
    return self;
}

- (void) Reset{
    [super initWithContentRect: CGRectMake(0.0f, 0.0f, BUTTON_WIDTH , BUTTON_HEIGHT)];
    [self orderFront: self];
    [self setContentView: viewM];
    [self reposition];
	[self StartTimer];
}

- (id) dealloc
{
   [viewM release];
   [super dealloc];
}


- (id) StartTimer
{
    [self StopTimer]; // in case "start" is called twice
    // create our timer
    timerM = [NSTimer scheduledTimerWithTimeInterval: tickIntervalM
                target: self
                selector: @selector(tick:)
                userInfo: nil
                repeats: YES];
}

- (id) StopTimer
{
    if (timerM) {
        [timerM invalidate];
        timerM = nil;
    }
}

- (id) tick: (NSTimer *)timer
{
   [super orderFront: self]; // bring to front
   [super makeKey: self];
}

- (id) reposition
{
	int barHeight = [UIHardware statusBarHeight];
	int minx = 0;
	int maxx = (320 - BUTTON_WIDTH);
	int miny = (0 - barHeight);
	int maxy = (480 - BUTTON_HEIGHT - barHeight);
	
	if (_x < minx) _x = minx;
	if (_x > maxx) _x = maxx;
	if (_y < miny) _y = miny;
	if (_y > maxy) _y = maxy;
	
    [super setTransform: CGAffineTransformMakeTranslation(_x, _y)];
}

- (BOOL) ignoresMouseEvents
{
    return NO;//stateM != kAntAlive;
}
- (void)mouseDragged: (void *) event {
	CGRect loc = GSEventGetLocationInWindow(event);
	CGPoint p = [self convertWindowToDevice: loc.origin];
	m_moving = true;
	_x = _basex + (p.x-_initx);
	_y = _basey + (p.y-_inity);
    [self reposition];
}
- (void)mouseUp: (void *) event {
	if (m_moving) {
		[mConfig xSet: _x];
		[mConfig ySet: _y];
	    [mConfig SaveDefaults];
	}
	else{
		[mParent Start];
	}
}

- (void) mouseDown: (void *) event {
	CGRect loc = GSEventGetLocationInWindow(event);
	CGPoint p = [self convertWindowToDevice: loc.origin];
	m_moving = false;
	_initx = p.x;
	_inity = p.y;
	_basex = _x;
	_basey = _y;
}

@end
